// miniprogram/pages/newmain_management_t/homePageManguagement.js
Page({
  _confirm: function (e) {
    console.log(e)
    this.setData({
      need_delete_id: e.target.id,
      need_delete_type: e.target.dataset.type
    })
    this.setData({
      confirm: false
    })
  },
  _closeConfirm: function () {
    this.setData({
      confirm: true
    })
  },
  _delete: function () {
    // 在数据库中执行删除操作
    wx.cloud.database().collection('newmain_test').where({
      _id: this.data.need_delete_id
    }).remove().then(res => {
      console.log('delete res=',res)
      this.openToast()
      let a = []
      let t = this.data.need_delete_type
      for (let i = 0, l = this.data[t].length; i < l; i++) { //遍历每一个元素，id不符合的复制到新数组中
        if (this.data[t][i]._id != this.data.need_delete_id) {
          a.push(this.data[t][i])
        }
      }
      this.setData({
        [t]: a
      })
    }).catch(err => {
      console.log(err)
    })
    // 然后删除对话框
    this.setData({
      confirm: true
    })
  },
  /*操作成果或失败的提示*/
  openToast: function () {
    this.setData({
      toast: true
    });
    setTimeout(() => {
      this.setData({
        hideToast: true
      });
      setTimeout(() => {
        this.setData({
          toast: false,
          hideToast: false,
        });
      }, 300);
    }, 1500);
  },
  openWarnToast: function () {
    this.setData({
      warnToast: true
    });
    setTimeout(() => {
      this.setData({
        hidewarnToast: true
      });
      setTimeout(() => {
        this.setData({
          warnToast: false,
          hidewarnToast: false,
        });
      }, 300);
    }, 1500);
  },
  _add: function (e) {
    console.log(e)
    let type = e.currentTarget.id
    if (type == 'hots') {
      this.data.isChangeHot = true //用于 半页的弹窗 最后在发送时判断是不是在添加本月的热点
    }
    this.setData({
      dialog2: false,
      categories: this.data.sections[type]
    })
  },
  /*picker的选择改变*/
  _bindPickerChange: function (e) {
    console.log(e)
    let index = e.detail.value
    let c = this.data.categories[index]
    let old_str = this.data.pickerText
    this.setData({
      pickerText: c
    })
    // return undefined
    if (old_str != c) {
      this.setData({
        details: []
      })
      wx.cloud.database().collection('resources').where({
        category: c
      }).field({
        title: true,
        _id: true,
        category: true
      }).limit(20).get().then(res => {
        console.log(res)
        this.setData({
          details: this.data.details.concat(res.data)
        })
        if (res.data.length == 20) {
          this.setData({
            canReachBottom: true
          })
        }
      })
    }
  },
  /*checkboxgroup*/
  _checkboxChange: function (e) {
    console.log(e)
    this.data.checkBoxValues = e.detail.value
  },
  _closeHalfScreenDialog: function () {
    this.setData({
      dialog2: true
    })
  },
  _addRes: function (e) {
    console.log('_addRes')
    //添加到数据库中
    let l = this.data.checkBoxValues.length
    this.data['oldCheckBoxValues'] = []
    for (let i = 0; i < l; i++) {
      let t = this.data.checkBoxValues[i].split(',') //[id, category]
      let id = t[0]
      let c = this.data.cDict[t[1]] // c应该是根据用户点击的内容来
      console.log('t = ', t, 'c=', c)
      let title = t[2]
      if (this.data.isChangeHot == true) {
        this.setData({
          hots: this.data.hots.concat([{
            id,
            title
          }])
        })
        wx.cloud.database().collection('newmain_test').add({
          data: {
            rid: id,
            class: c,
            isHot: true,
            title: title
          },
          success: function (res) {
            console.log(res)
          },
          fail: function (err) {
            console.log(err)
          }
        })
      } else {
        this.setData({
          [c]: this.data[c].concat([{
            id,
            title
          }])
        })
        wx.cloud.database().collection('newmain_test').add({
          data: {
            rid: id,
            class: c,
            isHot: false,
            title: title
          },
          success: function (res) {
            console.log(res)
          },
          fail: function (err) {
            console.log(err)
          }
        })
      }

    }
    //添加完毕后要把下一次点击“添加”时弹出的弹框恢复到原来状态
    this.setData({
      checkBoxValues: [],
      isChangeHot: false
    })
    //最后关闭弹窗
    this._closeHalfScreenDialog();
  },
  _loadmore: function () {
    if (this.data.canReachBottom) {
      this.data.canReachBottom = false
      console.log('上拉刷新') //调用函数时，如果返回的结果数等于20个，则在函数中设置为true，否则，不设置
      wx.cloud.database().collection('resources').where({
          category: this.data.pickerText
        }).field({
          title: true,
          _id: true
        })
        .skip(this.data.details.length).limit(20).get().then(res => {
          console.log(res)
          this.setData({
            details: this.data.details.concat(res.data)
          })
          if (res.data.length == 20) {
            this.setData({
              canReachBottom: true
            })
          }
        })
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    /*资源数据*/
    hots: [], //{rid, title}
    knowledge: [],
    edu: [],
    law: [],
    history: [],
    work: [],
    /*操作相关*/
    confirm: true,
    need_delete_id: '123', //需要删除的id
    need_delete_type: '', //需要删除的id
    toast: false,
    warnToast: false,
    hideToast: false,
    hideWarnToast: false,
    dialog2: true,
    pickerText: '请选择分类',
    lanmu: [{
      id: 'hots',
      name: '本月热点设置'
    }, {
      id: 'knowledge',
      name: '保密知识栏目设置'
    }, {
      id: 'edu',
      name: '保密警示教育栏目设置'
    }, {
      id: 'law',
      name: '保密法律法规栏目设置'
    }, {
      id: 'history',
      name: '保密史栏目设置'
    }, {
      id: 'work',
      name: '当前形势下的保密工作设置'
    }],
    categories: [],
    sections:{
      "hots":['保密法、保密实施条例及相关法律法规', '保密管理规定、办法', '政策解读', '书籍推荐', '保密传统教育', '红色保密史、人物', '历代保密那些事', '保密防范技能', '保密常识', '保密管理知识：政策解读', '先进事迹', '泄密案例', '当前形势下的保密工作'],
      "law": ["保密法、保密实施条例及相关法律法规", "保密管理规定、办法", "政策解读", "书籍推荐"],
      "knowledge": ["保密防范技能", "保密常识", "保密管理知识"],
      "edu": ["先进事迹", "泄密案例"],
      "history": ["保密传统教育", "红色保密史、人物", "历代保密那些事"],
      "work": ["当前形势下的保密工作"]
    },
    details: [],
    checkBoxValues: [],
    isChangeHot: false,
    canReachBottom: false,
    cDict: {
      '保密法、保密实施条例及相关法律法规': 'law',
      '保密管理规定、办法': 'law',
      '政策解读': 'law',
      '书籍推荐': 'law',
      '保密传统教育': 'history',
      '红色保密史、人物': 'history',
      '历代保密那些事': 'history',
      '当前形势下的保密工作': 'work',
      '保密防范技能': 'knowledge',
      '保密常识': 'knowledge',
      '保密管理知识：政策解读': 'knowledge',
      '先进事迹': 'edu',
      '泄密案例': 'edu'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const collection = wx.cloud.database().collection('newmain_test')
    collection.count().then(res => {
      let total = res.total
      const batchTimes = Math.ceil(total / 20)
      const tasks = []
      for (let i = 0; i < batchTimes; i++) {
        const promise = collection.field({
          _id: true,
          rid: true,
          title: true,
          isHot: true,
          class: true
        }).skip(i * 20).limit(20).get().then(res => {
          return res.data
        }).catch(err => {
          return err
        }) //同时还会返回id即：{_id, rid, title}
        tasks.push(promise)
      }
      // 等待所有
      Promise.all(tasks).then(res => {
        res = res[0]
        for (let i = 0, l = res.length; i < l; i++) {
          let item = res[i]
          if (item.isHot) {
            this.setData({
              hots: this.data.hots.concat([item])
            })
          } else {
            let c = item.class
            this.setData({
              [c]: this.data[c].concat([item])
            })
          }
        }
      }).catch(err => {
        console.log(err)
      })
    }).catch(err => {
      console.log(err)
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})